import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { Inform } from './entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { CreateInformDto } from './dto/create-inform-dto';
import { UpdateInformDto } from './dto/update-inform-dto';

@Injectable()
export class InformService {
  @InjectRepository(Inform)
  private repository: Repository<Inform>;
  async create(createInformDto: CreateInformDto) {
    this.repository.save({
      content: createInformDto.content,
      // userId: 1,
    });
    return '新增成功';
  }

  async list(
    pageNum: number,
    pageSize: number,
    content: string,
    type: string,
    status: string,
  ) {
    if (!pageNum) {
      pageNum = 1;
    }
    if (!pageSize) {
      pageSize = 10;
    }
    const skipCount = (pageNum - 1) * pageSize;
    const condition: Record<string, any> = {};
    condition.isDetele = '1';
    if (content) {
      condition.content = Like(`%${content}%`);
    }
    if (type) {
      condition.type = type;
    }
    if (status) {
      condition.status = status;
    }
    const [inform, total] = await this.repository.findAndCount({
      where: condition,
      select: ['id', 'content', 'type', 'status', 'createTime', 'updateTime'],
      skip: skipCount,
      take: pageSize,
    });
    const newList = {
      list: inform,
      pageNum,
      pageSize,
      total,
    };
    return newList;
  }

  async update(updateInformDto: UpdateInformDto) {
    const inform = await this.repository.findOneBy({
      isDetele: '1',
      id: updateInformDto.id,
    });
    if (!inform) {
      throw new HttpException('此消息不存在，修改失败', HttpStatus.BAD_REQUEST);
    }
    inform.content = updateInformDto.content;
    await this.repository.update(
      {
        id: updateInformDto.id,
      },
      inform,
    );
    return '修改成功';
  }

  async remove(id: number) {
    // 数据删除
    // const res = await this.repository.delete({
    //   id,
    // });
    // if (!res) {
    //   throw new HttpException('未找到此消息，删除失败', HttpStatus.BAD_REQUEST);
    // }
    // 业务逻辑删除 (推荐)
    const inform = await this.repository.findOneBy({
      id,
    });
    if (!inform) {
      throw new HttpException('此消息不存在，删除失败', HttpStatus.BAD_REQUEST);
    }
    inform.isDetele = '0';
    await this.repository.update(
      {
        id,
      },
      inform,
    );

    return '删除成功';
  }
}
